import cheerio from 'react-native-cheerio';
import util from 'util';

import Book from "./entity/Book";
import Chapter from "./entity/Chapter";
import Content from "./entity/Content";

import tool from '../utils/tool';
import http from "../utils/http";

import '../utils/gbk';

let URL_SEARCH = "https://www.230book.com/modules/article/search.php?searchkey=%s&searchtype=articlename";
let URL_HOME = "https://www.230book.com";

const search = (keyword) => {
    let fetch_promise = new Promise(async (resolve, reject) => {
        try {
            // android 5.0 以下会出现 Network Request Failed
            // https://blog.csdn.net/u011562187/article/details/79476273
            let url = util.format(URL_SEARCH, $URL.encode(keyword));
            fetch(url)
                .then(res => {
                    return res.blob().then(blob => tool.readBlobAsText(blob, "GBK"));
                    // return res.text();
                })
                .then(data => {
                    const $ = cheerio.load(data);
                    let books = $('#content #nr').map(function (i, el) {
                        let x = $(this).html();
                        let title = $('td', this).eq(0).children('a').text();
                        let href = $('td', this).eq(0).children('a').attr('href');
                        let author = $('td', this).eq(2).text();
                        let book = new Book(href, title, author);
                        book.source = api.id;
                        return book;
                    });
                    let arr = tool.toArray(books);
                    resolve(arr);
                }).catch(err => {
                reject(err);
            });
        } catch (e) {
            reject(e);
        }
    });

    return new Promise(async (resolve, reject) => {
        http.fetchWithTimeout(fetch_promise)
            .then(res => resolve(res))
            .catch(err => reject(err))
        ;
    });
};

const chapters = (bookId) => {
    let fetch_promise = new Promise(async (resolve, reject) => {
        fetch(bookId)
            .then(res => {
                return res.blob().then(blob => tool.readBlobAsText(blob, "GBK"));
                // return res.text();
            })
            .then(data => {
                const $ = cheerio.load(data);
                let chapters = $('#list li a').map(function (i, el) {
                    let href = bookId + $(this).attr('href');
                    let text = $(this).text();
                    let c = new Chapter(text, href);
                    return c;
                });
                let arr = tool.toArray(chapters);
                resolve(arr);
            }).catch(err => {
            reject(err);
        });
    });

    return new Promise(async (resolve, reject) => {
        http.fetchWithTimeout(fetch_promise)
            .then(res => resolve(res))
            .catch(err => reject(err))
        ;
    });
};

const content = (link) => {
    let fetch_promise = new Promise(async (resolve, reject) => {
        fetch(link).then(res => {
            return res.blob().then(blob => tool.readBlobAsText(blob, "GBK"));
            // return res.text();
        }).then(data => {
            const $ = cheerio.load(data, {decodeEntities: false});
            let title = $('.bookname h1').text();
            let body = $('#content').html();
            body = tool.replace(body, '<br>', '\n');
            body = tool.replace(body, '&nbsp;', '');
            body = tool.replace(body, '    ', '');
            body = tool.replace(body, '　　', '');
            body = tool.replace(body, '\u3000\u3000', '');
            body = tool.replace(body, '\n\n', '\n');
            let c = new Content(title, body);
            resolve(c);
        }).catch(err => {
            reject(err);
        });
    });

    return new Promise(async (resolve, reject) => {
        http.fetchWithTimeout(fetch_promise)
            .then(res => resolve(res))
            .catch(err => reject(err))
        ;
    });
};

const api = {
    id: 'book230.com',
    name: '顶点小说(230book.com)',
    homepage: URL_HOME,
    search: search,
    chapters: chapters,
    content: content
};

export default api;
